<template>
  <div class="chatContainer">
    <div class="roomWrapper">
      <div class="item" v-for="(el, index) in chatList" :key="index">
        <div class="txt" v-if="el.type === 'txt'">
          {{ el.value }}
        </div>
        <show-media
          v-else-if="el.type === 'media'"
          :fileLink="el.value"
        ></show-media>
      </div>
    </div>
    <div class="operateBox">
      <div class="icons">
        <input type="file" id="chooseFileInput" />
        <div class="icon">
          <icon-image size="30px" />
        </div>
      </div>
      <div class="btnPosition">
        <a-button
          @click="sendMsg"
          style="background-color: rgb(3, 169, 244)"
          type="primary"
          status="danger"
          >send</a-button
        >
      </div>
      <a-textarea
        v-model="inputVal"
        placeholder="Please enter something"
        allow-clear
      />
    </div>
  </div>
</template>

<script setup>
  import { Message } from '@arco-design/web-vue';
  import { onMounted, ref } from 'vue';
  import { chatRoomFileDomain } from '@/templateDir/utils/common';
  import { updateChatRoomFile } from '@/api/common';

  import ShowMedia from './showMedia.vue';

  const chatList = ref([]);

  const ws = ref(null);

  const imgVal = ref('');

  const inputVal = ref('');

  const sendMsg = () => {
    if (inputVal.value?.trim()) {
      ws.value.send(
        JSON.stringify({
          type: 'txt',
          value: inputVal.value,
        })
      );
      inputVal.value = '';
    }
  };

  onMounted(() => {
    const domInput = document.querySelector('#chooseFileInput');

    domInput.addEventListener('change', () => {
      const file = domInput.files[0];

      if (file) {
        const formData = new FormData();
        formData.append('file', file);
        updateChatRoomFile(formData)
          .then((res) => {
            const link = chatRoomFileDomain + res?.data;

            ws.value.send(
              JSON.stringify({
                type: 'media',
                value: link,
              })
            );
          })
          .catch((err) => {
            onError(err);
          });

        // 文件已选择
        console.log('文件已选择：' + file.name);
      } else {
        // 文件未选择
        console.log('文件未选择');
      }
    });

    document.addEventListener('mousemove', (event) => {
      document.title = '聊天室';
    });

    document.addEventListener('keydown', (event) => {
      if (event.keyCode === 13 || event.keyCode === 13) {
        sendMsg();
      }
    });

    let loginInfo = localStorage.getItem('login-config');

    try {
      loginInfo = JSON.parse(loginInfo);
    } catch (error) {}

    ws.value = new WebSocket(
      `ws://blog.shilinwei.com:81/chatRoom/${loginInfo.username}`
      // `ws://localhost:1007/chatRoom/${loginInfo.username}`
    );

    ws.value.onopen = () => {
      ws.value.send(
        JSON.stringify({
          type: 'ping',
        })
      );
    };

    ws.value.onmessage = (message) => {
      let msg = JSON.parse(message.data);
      if (msg.type === 'txt') {
        chatList.value.push({
          type: 'txt',
          value: msg.value,
        });

        if (document.hidden) {
          document.title = '您有一条消息待阅读';
        } else {
          document.title = '聊天室';
        }
      } else if (msg.type === 'ping') {
        setTimeout(() => {
          ws.value.send(
            JSON.stringify({
              type: 'ping',
            })
          );
        }, 20 * 1000);
      } else if (msg.type === 'media') {
        chatList.value.push({
          type: 'media',
          value: msg.value,
        });

        if (document.hidden) {
          document.title = '您有一条消息待阅读';
        } else {
          document.title = '聊天室';
        }
      }
    };
  });
</script>

<style lang="less" scoped>
  .chatContainer {
    width: 100vw;
    height: 100vh;
    background: rgb(41, 49, 75);
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    .operateBox {
      width: 1200px;
      max-width: 80%;
      height: 200px;
      background: rgb(54, 67, 101);
      margin-top: 20px;
      border-radius: 10px;
      position: relative;
      overflow: hidden;
      .btnPosition {
        position: absolute;
        bottom: 10px;
        right: 10px;
        z-index: 10;
      }
      .icons {
        width: 40px;
        height: 40px;
        padding: 10px;
        box-sizing: border-box;
        position: relative;
        input {
          top: 0;
          left: 0;
          right: 0;
          bottom: 0;
          position: absolute;
          z-index: 3;
          opacity: 0;
          cursor: pointer;
        }
        .icon {
          top: 0;
          left: 0;
          right: 0;
          bottom: 0;
          position: absolute;
          z-index: 2;

          display: flex;
          align-items: center;
          justify-content: center;
        }
      }
      /deep/ .arco-textarea-wrapper {
        border: none;
        background: transparent;
      }
      /deep/ textarea {
        background: rgb(60, 68, 91);
        font-size: 16px;
        color: #fff;
        letter-spacing: 1px;
        height: 160px;
        border: 1px solid rgb(60, 68, 91);
        outline: none;
        resize: none;
        // box-shadow: rgb(18, 120, 176) 0px 0px 0px 1px inset,
        //   rgb(29, 85, 125) 0px 0px 0px 3px;
      }
    }
    .roomWrapper {
      width: 1200px;
      max-width: 80%;
      height: 500px;
      background: rgb(54, 67, 101);
      padding: 20px;
      border-radius: 10px;
      overflow: auto;
      .item {
        color: #fff;
        margin-bottom: 20px;
      }
    }
  }
</style>
